<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>  
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card shadow="hover">
      <!-- 警告区域 -->
      <el-alert show-icon title="注意：只允许设置三级分类！" type="warning" :closable="false"></el-alert>
      <!-- 选择商品分类区域 -->
      <el-row class="cate-option">
        <el-col :span="3">选择商品分类：</el-col>
        <!-- 级联选择器 -->
        <el-col :span="21">
          <el-cascader 
            :props="cascaderProps"
            :options="goodsAllCateList" 
            v-model="selectedKeys"
            @change="parentCateChanged"
            clearable>
          </el-cascader>
        </el-col>
      </el-row>
      <!-- tab管理区域 -->
      <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
        <!-- 添加参数 -->
        <el-tab-pane label="动态参数" name="many">
          <el-button type="primary" :disabled="isDisable" @click="dialogVisible=true">添加参数</el-button>
          <!-- 动态参数表格 -->
          <el-table :data="manyTableData">
            <!-- 展开行 -->
            <el-table-column type="expand" label="#">
              <!-- attr_vals -->
              <template slot-scope="scope">
                <el-tag closable v-for="(item,index) in scope.row.attr_vals" :key="index"
                @close="handleClose(index,scope.row)">{{item}}</el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInputRef"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)">
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>

              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index" label="#"></el-table-column>
            <!-- 参数名称 -->
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <!-- 操作 -->
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button size="mini" type="primary" icon="el-icon-edit" @click="showEditDialog(scope.row.attr_id)">编辑</el-button>
                <el-button size="mini" type="danger" icon="el-icon-delete" @click="removeParams(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 添加属性 -->
        <el-tab-pane label="静态属性" name="only">
          <el-button type="primary"  :disabled="isDisable" @click="dialogVisible=true">添加参数</el-button>
          <!-- 静态属性表格 -->
          <el-table :data="onlyTableData">
            <!-- 展开行 -->
            <el-table-column type="expand" label="#">
              <!-- attr_vals -->
              <template slot-scope="scope">
                <el-tag closable v-for="(item,index) in scope.row.attr_vals" :key="index"
                @close="handleClose(index,scope.row)">{{item}}</el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInputRef"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)">
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>

              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index" label="#"></el-table-column>
            <!-- 参数名称 -->
            <el-table-column label="属性名称" prop="attr_name"></el-table-column>
            <!-- 操作 -->
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button size="mini" type="primary" icon="el-icon-edit" @click="showEditDialog(scope.row.attr_id)">编辑</el-button>
                <el-button size="mini" type="danger" icon="el-icon-delete" @click="removeParams(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
      <!-- 添加参数或属性的对话框 -->
      <el-dialog :title="'添加'+textTitle" :visible.sync="dialogVisible" width="30%" @close="addDialogClose">
        <el-form :model="addParamsForm" :rules="addParamsFormRules" ref="addParamsFormRef" label-width="100px">
          <el-form-item :label="textTitle" prop="attr_name">
            <el-input v-model="addParamsForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addDialogbtn">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 修改参数的对话框 -->
      <el-dialog :title="'编辑'+textTitle" :visible.sync="editDialogVisible" width="30%" @close="editDialogClose">
        <el-form :model="editParamsForm" :rules="editParamsFormRules" ref="editParamsFormRef" label-width="100px">
          <el-form-item :label="textTitle" prop="attr_name">
            <el-input v-model="editParamsForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible=false">取 消</el-button>
          <el-button type="primary" @click="editDialogbtn">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>
<script>
import {goodsCateListReq,paramsReq,addParamsReq,editParamsReq,queryParamsReq,deleteParamsReq} from '../../networks/goods'
export default {
  name:'Params',
  data() {
    return {
      // 请求参数设置
      queryInfo:{},
      // 商品分类信息
      goodsAllCateList:[],
      //配置级联对象
      cascaderProps:{
        // 级联展开方式
        expandTrigger:"hover",
        // 实际的数据值
        value:"cat_id",
        // 所看到的选项
        label:"cat_name",
        //指定父子嵌套使用哪个属性
        children:"children",
      },
      //级联选中项
      selectedKeys:[],
      //动态绑定的活跃的tab
      activeName:'many',
      // 保存参数和属性的数据
      manyTableData:[],
      onlyTableData:[],
      //控制添加显示与隐藏
      dialogVisible:false,
      // 添加参数或者属性表单绑定的数据对象
      addParamsForm:{
        attr_name:'',
      },
      // 添加参数或者属性表单绑定的规则对象
      addParamsFormRules:{
        attr_name:[ { required: true, message: '请输入参数', trigger: 'blur' },]
      },
      //控制编辑显示与隐藏
      editDialogVisible:false,
      // 编辑参数或者属性表单绑定的数据对象
      editParamsForm:{
        attr_name:'',
      },
      // 编辑参数或者属性表单绑定的规则对象
      editParamsFormRules:{
        attr_name:[ { required: true, message: '请输入参数', trigger: 'blur' },]
      },
     

    }
  },
  created() {
    this.goodsCateList();
  },
  computed:{
    // 控制btn添加参数和属性的显示和隐藏
    isDisable(){
      if(this.selectedKeys.length===3){ return false};
      return true;
    },
    //分类id
    cateId(){
      if(this.selectedKeys.length===3){
        return this.selectedKeys[2];
      }else{
        return null;
      }
    },
    textTitle(){
      if(this.activeName==="many"){
        return "动态参数";
      }else{
        return "静态属性";
      }
    }
  },
  
  methods: {
    // 商品分类列表请求方法
    goodsCateList(){
      //请求商品分类数据列表
      goodsCateListReq("categories",this.queryInfo).then(res=>{
        console.log(res,"goodsCateListReq");
        if(res.meta.status!==200) return this.$message.error(res.meta.msg);
        //成功，数据保存
        console.log(res.data,"goodsCateListReq");
        this.goodsAllCateList=res.data;
        console.log(this.goodsAllCateList,"goodsAllCateList");
      })
    },
    //级连选项发生变化
    parentCateChanged(){
      console.log(this.selectedKeys);
      this.getParamsData();
    },
    getParamsData(){
      //首先判断级联是否为三级
      if(this.selectedKeys.length!==3){
        this.selectedKeys=[];
        this.manyTableData=[];
        this.onlyTableData=[];
        return;
      }
       //请求参数和属性
      paramsReq(`categories/${this.cateId}/attributes`,{sel:this.activeName}).then(res=>{
        console.log(res,"paramsReq");
        if(res.meta.status!==200) return this.$message.error("获取动态参数和静态属性失败！");
        // 分开保存参数和属性的数据
          res.data.forEach(item => {
          //  判断attr_vals是否为空
          item.attr_vals=item.attr_vals? item.attr_vals.split(","):[];
          // console.log("item-attr-value",item.attr_vals);
          // 为个参数添加inputVisible:false,inputValue:"",
          item.inputVisible=false;
          item.inputValue="";
        });
        if(this.activeName==="many"){
          this.manyTableData=res.data;
        }else{
          this.onlyTableData=res.data;
        }
      })
    },
    // tab标签发生变化
    handleClick(){
      console.log(this.activeName,"activeName");
      // 请求参数数据
      this.getParamsData();
    },
    //监听对话框关闭
    addDialogClose(){
      this.$refs.addParamsFormRef.resetFields();
    },
    //监听添加参数确定按钮
    addDialogbtn(){
      //表单与验证
      this.$refs.addParamsFormRef.validate(valid=>{
        if(!valid) return ;
        // 请求添加参数方法
        addParamsReq(`categories/${this.cateId}/attributes`,{attr_name:this.addParamsForm.attr_name,attr_sel:this.activeName}).then(res=>{
          console.log(res,"addParamsReq");
          if(res.meta.status!==201) return this.$message.error("添加失败！");
          this.$message.success("添加成功!")
          this.getParamsData();
          this.dialogVisible=false;
        })
      })
    },
    //监听对话框关闭
    editDialogClose(){
      this.$refs.editParamsFormRef.resetFields();
    },
    //监听编辑参数确定按钮
    editDialogbtn(){
      //表单与验证
      this.$refs.editParamsFormRef.validate(valid=>{
        console.log(valid);
        if(!valid) return;
        //请求修改
        editParamsReq(`categories/${this.cateId}/attributes/${this.editParamsForm.attr_id}`,{attr_name:this.editParamsForm.attr_name,attr_sel:this.activeName}).then(res=>{
          console.log(res,"editParamsReq");
          if(res.meta.status!==200) return this.$message.error("更新失败！");
          this.$message.success("修改成功！");
          this.getParamsData();
          this.editDialogVisible=false;
        })

      })
    },
    //监听编辑按钮的点击显示
    showEditDialog(attr_id){
      this.editDialogVisible=true;
      queryParamsReq(`categories/${this.cateId}/attributes/${attr_id}`,{
        attr_sel:this.activeName
      }).then(res=>{
        // console.log(res,"queryParamsReq");
        if(res.meta.status!==200) return this.$message.error("获取参数信息失败！");
        this.editParamsForm=res.data;
        // console.log(this.editParamsForm,"showEditDialog");
      })
      
    },
    removeParams(attr_id){
      this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(res=>{
        //发送删除请求
        deleteParamsReq(`categories/${this.cateId}/attributes/${attr_id}`).then(res=>{
          console.log(res,"deleteParamsReq");
          if(res.meta.status!==200) return this.$message.error("删除参数失败！");
          this.getParamsData();
          this.$message.success("删除成功！");
        })

      }).catch(err=>{
        this.$message.error("已取消删除操作！")
      })
    },
    //监听切换输入框的鼠标和失去焦点事件
    handleInputConfirm(row){
      //输入数据不合法
      if(row.inputValue.trim().length===0){
        row.inputValue="";
        row.inputVisible=false;
        return;
      }else{
        row.attr_vals.push(row.inputValue);
        row.inputValue="",
        row.inputVisible=false;
        // 将操作编辑保存到数据库里
        editParamsReq(`categories/${this.cateId}/attributes/${row.attr_id}`,
        {attr_name:row.attr_name,attr_vals:row.attr_vals.join(","),attr_sel:this.activeName}).then(res=>{
          console.log(res,"tageditParamsReq");
          if(res.meta.status!==200) return this.$message.error("添加参数失败!");
          
          this.$message.success("更新成功！");
        })
      }
      
    },
 
    // 监听按钮控制是否显示input
    showInput(row){
      row.inputVisible=true;
      //文本框自动获得焦点
      //页面重新渲染，回调函数
      //如果放在外，虽然inutvisible为true,但是没有渲染出来，拿不到input,无法聚焦
      this.$nextTick(_ => {
        this.$refs.saveTagInputRef.$refs.input.focus();
      });
    },
    // 监听tag标签的关闭事件
    handleClose(index,row){
      //删除对应的参数
      row.attr_vals.splice(index,1);
      editParamsReq(`categories/${this.cateId}/attributes/${row.attr_id}`,
        {attr_name:row.attr_name,attr_vals:row.attr_vals.join(","),attr_sel:this.activeName}).then(res=>{
          console.log(res,"tageditParamsReq");
          if(res.meta.status!==200) return this.$message.error("删除参数失败!");
          
          this.$message.success("删除成功！");
        })
    }
    
  }
}
</script>
<style scoped>
.cate-option{
  margin: 15px 0;
  display: flex;
  align-items: center;
}
.el-tag{
  margin-right:10px;
}
.input-new-tag{
  width:120px;
}
</style>